from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

# Create your views here.
from api import models
from api.ser import BookModelSerializer
from utils.throttling import MyThrottle


class BookAPIView(APIView):
    def get(self, request, *args, **kwargs):
        """
        APIView 方法的文档接口测试
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 查询单个和查询所有，合到一起
        book_list = models.Book.objects.all().filter(is_delete=False)
        book_list_ser = BookModelSerializer(instance=book_list, many=True)
        print(book_list_ser, type(book_list_ser))  # <class 'api.ser.BookModelSerializer'>
        return Response(data=book_list_ser.data)

    # 增一条与增多条
    def post(self, request, *args, **kwargs):
        """
        APIView 方法的文档接口测试
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 批量增
        print(request.data)
        if isinstance(request.data, dict):
            book_ser = BookModelSerializer(data=request.data)
            print(book_ser, type(book_ser))
            book_ser.is_valid(raise_exception=True)
            book_ser.save()
            return Response(data=book_ser.data)
        elif isinstance(request.data, list):
            book_ser = BookModelSerializer(data=request.data, many=True)  # 增多条 many=True后 就变成了
            print(book_ser, type(book_ser))  # <class 'rest_framework.serializers.ListSerializer'>
            book_ser.is_valid(raise_exception=True)
            book_ser.save()  # 调用ListSerializer的create方法
            return Response(data=book_ser.data)

    # 改一个与改多个
    def put(self, request, *args, **kwargs):
        # 改一个
        pk = kwargs.get('pk', None)
        print(pk)
        if pk:
            book = models.Book.objects.filter(pk=pk).first()
            book_ser = BookModelSerializer(instance=book, data=request.data, partial=True)  # partial=True 传几个改几个
            book_ser.is_valid(raise_exception=True)
            book_ser.save()
            return Response(book_ser.data)
        else:
            # 要求前端传过来的数据 [{'id': 1, 'name': xx, 'price': 14}, {'id': 2, 'name': xx, 'price': 14}, ]
            # 处理传入的数据 对象列表[book1, book2]
            # 修改的数据列表[{'id': 1, 'name': xx, 'price': 14}, {'id': 2, 'name': xx, 'price': 14}, ]
            book_list = []
            modify_data = []
            for item in request.data:
                pk = item.pop('id')
                book = models.Book.objects.filter(pk=pk).first()
                book_list.append(book)
                modify_data.append(item)
            # 第一种方案 for循环 一个一个修改
            # for i, si_data in enumerate(modify_data):
            #     book_ser = BookModelSerializer(instance=book_list[i], data=si_data)
            #     book_ser.is_valid()
            #     book_ser.save()
            # return Response(book_ser.data)
            # 第二种方案，重写 ListSerializer 的update方法
            # book_ser = BookModelSerializer(instance='对象列表', data='修改的数据列表', many=True)  # 就会变成 ListSerializer
            # book_ser.is_valid(raise_exception=True)
            # book_ser.save()  # 调用 ListSerializer.update()方法 如何让重写的update方法跟BookModelSerializer建立关联
            book_ser = BookModelSerializer(instance=book_list, data=modify_data, many=True)
            book_ser.is_valid()
            book_ser.save()
            return Response(book_ser.data)

    def delete(self, request, *args, **kwargs):

        # 单个删除和批量删除
        pk = kwargs.get('pk')
        pks = []
        if pk:
            # 单挑删除
            pks.append(pk)

        # 不管单条删除或多条删除，都用多条删除
        else:
        # 多条删除
        # 规定传输过来的数据 {'pks': [1, 2, 3]}
            pks = request.data.get('pks')
        # 删除 将 is_delete=True
        print(pks)
        ret = models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True)  # 返回受影响的行数
        print(ret)
        if ret:
            return Response(data={'msg': '删除成功'})
        else:
            return Response(data={'msg': '没有要删除的数据'})


# 查所有分页
# 内值3中分页方式
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination


class MyPageNumberPagination(PageNumberPagination):
    page_size = 3
    page_query_param = 'current_page'
    page_size_query_param = 'size'  # 指定me一页的大小
    max_page_size = 5  # 路由后面page_size_query_param的参数值最大为 5


# class MyPageNumberPagination(LimitOffsetPagination):
#     limit_query_param = 'limits'  # 拼接在url后面的限制参数
#     offset_query_param = 'offset'
#     default_limit = 3
#     max_limit = 5  # 每页最多5条


# class MyPageNumberPagination(CursorPagination):  # 只有上一页下一页
#     cursor_query_param = 'cursors'  # 拼接在url后面的查询参数
#     page_size = 2
#     ordering = '-id'  # 排序字段


class BookView(ListAPIView):
    """
    PageNumberPagination
    page_size: 每页显示的条数
    page_query_param: 拼接在路由后面的参数
    返回所有图书

    """
    queryset = models.Book.objects.filter(is_delete=False).all()
    serializer_class = BookModelSerializer
    # pagination_class = PageNumberPagination
    pagination_class = MyPageNumberPagination
    filter_fields = ('name', 'publish')


class BookView2(APIView):
    # throttle_classes = [MyThrottle, ]

    def get(self, request, *args, **kwargs):
        """
        文档api说明
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        book_list = models.Book.objects.filter(is_delete=False).all()
        # 使用分页器
        page_cursor = MyPageNumberPagination()
        book_list = page_cursor.paginate_queryset(queryset=book_list, request=request, view=self)  # view 可以不传
        next_url = page_cursor.get_next_link()
        pr_url = page_cursor.get_previous_link()
        print(next_url, pr_url)
        book_ser = BookModelSerializer(instance=book_list, many=True)
        return Response(data=book_ser.data)
